package com.dongdongshop.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //实例化shiro的过滤器
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //定义过滤器
        Map<String,String> map = new LinkedHashMap<>(); //表示对于这种类型的map存取有序
        //先放过，再拦截，key是路径 value就是shiro中的过滤器
        map.put("/login","anon");// anon: 无需登录直接放过
        map.put("/getInfo","anon");
        map.put("/css/**","anon");
        map.put("/img/**","anon");
        map.put("/js/**","anon");
        map.put("/plugin/**","anon");

        map.put("/**","authc");// authc: 必须登录才能访问

        //跳转登录路径
        shiroFilterFactoryBean.setLoginUrl("/login");

        //需要将map放入过滤器工厂类中
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }

    //实例化安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm loginRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //设置realm
        defaultWebSecurityManager.setRealm(loginRealm);
        return defaultWebSecurityManager;
    }

    //实例化自定义的realm类
    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginRealm loginRealm = new LoginRealm();
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginRealm;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        //1.加密的工具类
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();

        //2.加密算法的名字
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");

        //3.加密的次数
        hashedCredentialsMatcher.setHashIterations(3);

        //4.是否要设置编码
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);

        return hashedCredentialsMatcher;
    }
}
